package work.shyk.kongMonitor.dto.param;

import com.fasterxml.jackson.databind.JsonNode;
import work.shyk.kongMonitor.dto.result.interfaces.ValueReceiver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * description: <br>
 * createTime: 2021/3/24 16:02 <br>
 *
 * @author zzh
 */
public class AggsTermsQuery extends AbstractAggsQuery{

    Terms terms;

    Map<String, DefaultAggsQuery> aggs = new HashMap<>();

    public AggsTermsQuery(String key) {
        super(key);
        put("aggs", aggs);
    }

    public AggsTermsQuery addTerms(String field) {
        terms = new Terms(field);
        put("terms", terms);
        return this;
    }

    public AggsTermsQuery setAggs(Map<String, DefaultAggsQuery> aggs) {
        this.aggs = aggs;
        put("aggs", aggs);
        return this;
    }

    public AggsTermsQuery addAggs(DefaultAggsQuery aggs) {
        this.aggs.put(aggs.getKey(), aggs);
        return this;
    }


    @Override
    public List<ValueReceiver> parse(JsonNode jsonNode, Supplier receiverSupplier) {
        List<ValueReceiver> result = new ArrayList();
        JsonNode buckets = jsonNode.get(key).get("buckets");
        for (JsonNode bucket : buckets) {
            ValueReceiver valueReceiver = (ValueReceiver) receiverSupplier.get();
            result.add(valueReceiver);
            for (Entry<String, DefaultAggsQuery> entry : aggs.entrySet()) {
                entry.getValue().parse(bucket, () -> valueReceiver);
            }
        }
        return result;
    }
}
